(function(window, angular, undefined){
	'use strict';
	var home = angular.module('home',[]);
	/*define var*/
	var config = {
		moduleName : home.name,
		tpl_folder : 'template',
	}
	var tpl_path = [rootConfig.moduleDir,config.moduleName,config.tpl_folder].join('/');
	var baseState = [config.moduleName].join('');
	var baseController = [config.moduleName].join('');
	var listState = [baseState,'list'].join('.');
	var listController = [baseState,'list'].join('.');
	
	var writeState = [baseState,'write'].join('.');
	var writeController = [baseState,'write'].join('.');
	
	home.config(function($stateProvider, $urlRouterProvider){
		$stateProvider
		    .state(baseState, {
		      url: '/home',
		      templateUrl: [tpl_path,'main.html'].join('/'),
		      controller : baseController
		    })
		    .state(listState,{
		    	url : '/list/:cat',
		    	template : '<div ng-include="getListTemplate()"></div>',
		    	controller : listController
		    })
		    .state(writeState,{
		    	url:'/write/:cat/:id',
		    	template : '<div ng-include="getWriteTemplate()"></div>',
		    	controller : writeController
		    })
	});
	home.controller(baseController, ['$scope','$http','$state','$rootScope','$stateParams',
		function ($scope,$http,$state,$rootScope,$stateParams) {
			$scope.listState = listState;//set dynamic state
			/* List menu */
			$scope.menu = 
			[
				{cat:'drink',text : 'Thức uống'},
				{cat:'employee',text:'Nhân Viên'},
				{cat:'table',text : 'Bàn'}
			];
	}])
	home.controller(listController, ['$scope','$state','$stateParams','homeService', function ($scope,$state,$stateParams,homeService) {
		var cat = $stateParams.cat;
		$scope.getListTemplate = function(){
			return [tpl_path,cat,'list.html'].join('/');
		}
		var url = [rootConfig.baseUrl,cat,cat,'list'].join('/');
		/*  Load data on page load */
		homeService.list(url).success(function(res){
			if(res.status){
				$scope.data = res.data;
			}
		});
		$scope.checkAll = function(all){
			if(all=='YES'){
				$scope.checkList = $scope.data.map(function(item){
					return item.id;
				});
			}else{
				$scope.checkList = [];
			}
		}
		$scope.goWrite = function(){
			$state.go(writeState,{cat:cat});
		}
		/* go State Edit */
		$scope.goEdit = function(item){
			$scope.$parent.item = item; // send data to edit
			$state.go(writeState,{cat:cat,id:item.id});
		}
		$scope.reload = function(){
			$state.reload();// config in rootApp
		}
		/* Delete item */
		$scope.del=function(key,item)
		{
			var item_id = item.id;
			var data = {
				id: item_id
			}
			var url = [rootConfig.baseUrl,cat,cat,'delete'].join('/');
			box.confirm('Bạn thực sự muốn xóa?','Xác nhận',function(ok){
				if(ok){
					homeService.delete(url,data).success(function(res)
					{
						if(res.status)
						{
							$scope.data.splice(key,1);
						}
					});
				}
			});		
		}
	}]);
	home.controller(writeController, ['$rootScope','$scope','$state','$stateParams','rootService','homeService',
		function ($rootScope,$scope,$state,$stateParams,rootService,homeService){
		$scope.formData = {};
		var cat = $stateParams.cat;
		$scope.getWriteTemplate = function(){
			return [tpl_path,cat,'write.html'].join('/');
		}

		/* Update set data Form*/
		if($stateParams.id){
			// check date form listController
			if($scope.$parent.item){
				$scope.$parent.item.price = parseInt($scope.$parent.item.price);
				$scope.formData = $scope.$parent.item;
			}else{
				var url = [rootConfig.baseUrl,cat,cat,'item',].join('/');
				homeService.getItem(url,{id:$stateParams.id}).success(function(res){
					if(res.status){
						res.data.price = parseInt(res.data.price);
						$scope.formData = res.data;
					}
				});
			}
		}
		$scope.add = function(){
			var data = $scope.formData;
			if($stateParams.id) data.id = $stateParams.id; //update flag
			var flag = rootService.validateForm(data);
			if(flag){
				rootConfig.loading(true,'form')
				var url = [rootConfig.baseUrl,cat,cat,'add'].join('/');
				homeService.add(url,data).success(function(res){
					if(res.status){
						$state.go(listState,{cat:cat});
					}else{
						box.alert('Thất bại!');
					}
				});
				rootConfig.loading(false);
			}
		}

	}])
	home.service('homeService', ['$http',function ($http) {

		return {
			add:function(url,data){
				return $http.post(url,data);
			},
			list : function(url){
				return $http.get(url);
			},
			getItem : function(url,params){
				return $http.post(url,params);
			},
			delete : function(url,params){
				return $http.post(url,params);
			}
		}
	}])
	home.directive('checklistModel', ['$parse', '$compile', function($parse, $compile) {
	  function contains(arr, item) {
	    if (angular.isArray(arr)) {
	      for (var i = 0; i < arr.length; i++) {
	        if (angular.equals(arr[i], item)) {
	          return true;
	        }
	      }
	    }
	    return false;
	  }

	  // add
	  function add(arr, item) {
	    arr = angular.isArray(arr) ? arr : [];
	    for (var i = 0; i < arr.length; i++) {
	      if (angular.equals(arr[i], item)) {
	        return arr;
	      }
	    }    
	    arr.push(item);
	    return arr;
	  }  

	  // remove
	  function remove(arr, item) {
	    if (angular.isArray(arr)) {
	      for (var i = 0; i < arr.length; i++) {
	        if (angular.equals(arr[i], item)) {
	          arr.splice(i, 1);
	          break;
	        }
	      }
	    }
	    return arr;
	  }

	  // http://stackoverflow.com/a/19228302/1458162
	  function postLinkFn(scope, elem, attrs) {
	    // compile with `ng-model` pointing to `checked`
	    $compile(elem)(scope);

	    // getter / setter for original model
	    var getter = $parse(attrs.checklistModel);
	    var setter = getter.assign;

	    // value added to list
	    var value = $parse(attrs.checklistValue)(scope.$parent);

	    // watch UI checked change
	    scope.$watch('checked', function(newValue, oldValue) {
	      if (newValue === oldValue) { 
	        return;
	      } 
	      var current = getter(scope.$parent);
	      if (newValue === true) {
	        setter(scope.$parent, add(current, value));
	      } else {
	        setter(scope.$parent, remove(current, value));
	      }
	    });

	    // watch original model change
	    scope.$parent.$watch(attrs.checklistModel, function(newArr, oldArr) {
	      scope.checked = contains(newArr, value);
	    }, true);
	  }

	  return {
	    restrict: 'A',
	    priority: 1000,
	    terminal: true,
	    scope: true,
	    compile: function(tElement, tAttrs) {
	      if (tElement[0].tagName !== 'INPUT' || !tElement.attr('type', 'checkbox')) {
	        throw 'checklist-model should be applied to `input[type="checkbox"]`.';
	      }

	      if (!tAttrs.checklistValue) {
	        throw 'You should provide `checklist-value`.';
	      }

	      // exclude recursion
	      tElement.removeAttr('checklist-model');
	      
	      // local scope var storing individual checkbox model
	      tElement.attr('ng-model', 'checked');

	      return postLinkFn;
	    }
	  };
	}]);
})(window, window.angular);


